#!/usr/bin/env python

from pyraf import iraf
from pyraf.iraf import pysoar
from pysoarlib import createfile_and_write,error
from string import Template
import os

def createpack(pkgname,rootpkg,verbose):
	'''
	This task intent to create a package for the rootpkg using templates for the addpath.py 
	and pkgname.cl files.
	'''
	d = dict(pkg=pkgname,root=rootpkg)
	
	#Setting the default filenames: addpath.py and *pkgname*.cl
	pkgcl = '%s.cl'%pkgname
	addpath = 'addpath.py' 

	#Setting the pathnames for each default files 
	path_pkg = iraf.osfn("%s$%s"%(rootpkg,pkgname))
	path_addpath = os.path.join(path_pkg,addpath)
	path_pkgcl   = os.path.join(path_pkg,pkgcl)

	#Here are the template texts for each file
	template_addpath = Template('''
""" Inserts the directory containing links to all Python-based tasks
    in the SOAR tree to the default Python path.
"""
import iraf,sys

# define and add path to top level Python directory in SOAR

_path = iraf.osfn('$root$$$pkg')
if _path not in sys.path:
	sys.path.insert(1,_path)
''').safe_substitute(d)

	template_pkgcl = Template('''# Package script for the SOAR 

#Package script tasks for $root

package $pkg

pyexecute("$root$$$pkg/addpath.py",verbose=no)
pyexecute("$root$$$pkg/temp.py",verbose=no) # edit this line to include new tasks

''').safe_substitute(d)

	#Creating the directory and the default files (if not exist).
	try:
		os.mkdir(path_pkg)
		createfile_and_write(path_addpath,template_addpath)
		createfile_and_write(path_pkgcl,template_pkgcl)
	except OSError:
		error('OSError:\nPackage directory %s already exist!'%path_pkg)
		pass

	finalmsg = Template('''
Edit the $root.cl to include the lines bellow:

	set $pkg   = "$root$$$pkg/"
	task ${pkg}.pkg    = $pkg$$$pkg.cl''').safe_substitute(d)
	print finalmsg
	
parfile = iraf.osfn("pysoar$soartools/createpack.par")
t = iraf.IrafTaskFactory(taskname="createpack",value=parfile,function=createpack)

